package com.fjw.servlet;

import com.fjw.entity.Student;
import com.fjw.service.StudentService;
import com.fjw.service.impl.StudentServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "studentServlet",urlPatterns = "/studentServlet")
public class StudentServlet  extends BaseServlet {
    private StudentService studentService =new StudentServiceImpl();


    public  void    goUpdate(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        //根据sid查询当前记录  返回给前端
        Student student = studentService.selectBySid(Integer.parseInt(sid));
        req.setAttribute("student",student);
        req.getRequestDispatcher("update.jsp").forward(req,resp);
    }


    public  void   update(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String sid = req.getParameter("sid");
        String sname = req.getParameter("sname");
        String sage = req.getParameter("sage");
        String sdesc = req.getParameter("sdesc");
        Student s =  new Student(Integer.parseInt(sid),sname,sdesc,Integer.parseInt(sage));
        //调用service
        int num = studentService.updateStudent(s);
        if(num >0){
            resp.sendRedirect("studentServlet?flag=selectAll");
        }else {
            resp.sendRedirect("studentServlet?flag=goUpdate");
        }
    }

    public  void delete(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String sid = req.getParameter("sid");
        //调用service层  执行删除
        int num = studentService.deleteBySid(Integer.parseInt(sid));
        resp.sendRedirect("studentServlet?flag=selectAll");
    }

    public  void  goAdd(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        resp.sendRedirect("add.jsp");
    }

    public  void  add(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String sname = req.getParameter("sname");
        String sage = req.getParameter("sage");
        String sdesc = req.getParameter("sdesc");
        Student s= new Student();
        s.setSname(sname);
        s.setSage(Integer.parseInt(sage));
        s.setSdesc(sdesc);

        int i = studentService.addStudent(s);
        resp.sendRedirect("studentServlet?flag=selectAll");
    }

    public  void selectAll(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        List<Student> studentList = studentService.selectAllList();
        req.setAttribute("studentList",studentList);

        //跳转页面
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}
